﻿import 'package:azring/pages/action/routes.dart';
import 'package:azring/pages/status/routes.dart';
import 'package:azring/pages/status/status_logic.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import '../../../core/repository/default_api.dart';

class CreatePlanLogic extends GetxController {
  final DefaultApi _api = DefaultApi();

  // 表单控制器
  final planNameController = TextEditingController();
  final stepCountController = TextEditingController();
  final durationController = TextEditingController();
  final exerciseCalorieController = TextEditingController();
  final dietCalorieController = TextEditingController();
  final customEventController = TextEditingController();

  // 响应式变量
  final isLoading = false.obs;
  final hasStepCountInput = false.obs;
  final recommendedDuration = 0.obs;
  final recommendedExerciseCalorie = 0.obs;
  final recommendedDietCalorie = 0.obs;
  final planCycle = 30.obs; // 默认30天
  final isDefaultPlan = true.obs;
  final hrvValue = ''.obs; // 心率变异性数值
  final isLoadingHrv = false.obs; // HRV加载状态
  final isLoadingFromApi = false.obs; // 标记是否正在从API加载数据
  
  // 查看/编辑模式
  final isViewMode = true.obs; // 是否为查看模式
  final isEditMode = false.obs; // 是否为编辑模式
  String? currentPlanId; // 当前计划ID
  String? currentPlanStatus; // 当前计划状态：'1'进行中 '2'已生成 '3'已完成
  
  // 从API加载的数据
  final sleepQuality = '良'.obs; // 睡眠质量
  final emotionManagement = '20-30'.obs; // 情绪管理压力值
  
  // 用于显示的响应式变量（解决TextEditingController不是响应式的问题）
  final planNameDisplay = ''.obs;
  final stepCountDisplay = ''.obs;
  final durationDisplay = ''.obs;
  final exerciseCalorieDisplay = ''.obs;
  final dietCalorieDisplay = ''.obs;

  // 事件打卡选项
  final selectedEvents = <String>[].obs;
  final availableEvents = <String>[
    '饮水 (> 1000 毫升)',
    '远眺 (> 5分钟)',
    '冥想 (> 10分钟)',
  ].obs;

  @override
  void onInit() {
    super.onInit();
    _setupListeners();
    _loadHrvInfo(); // 初始化时加载HRV数据

    // 如果有 planId，加载计划详情
    final arguments = Get.arguments as Map<String, dynamic>?;
    final planId = arguments?['planId'] as String?;
    // 如果有 planId，默认为查看模式；除非明确指定 isViewMode 为 false
    final viewMode = arguments?['isViewMode'] as bool? ?? (planId != null && planId.isNotEmpty);
    
    if (planId != null && planId.isNotEmpty) {
      currentPlanId = planId;
      isViewMode.value = viewMode;
      isEditMode.value = false;
      _loadPlanDetail(planId);
    } else {
      // 新建计划模式
      isViewMode.value = false;
      isEditMode.value = false;
    }
  }
  
  /// 切换到编辑模式
  void toggleEditMode() {
    isEditMode.value = !isEditMode.value;
  }

  /// 加载计划详情
  Future<void> _loadPlanDetail(String planId) async {
    try {
      isLoading.value = true;
      isLoadingFromApi.value = true; // 标记正在从API加载
      
      final response =
          await _api.queryHealthPlanDetailGet<Map<String, dynamic>>(
        queryId: planId,
        isShowErrMsg: false,
      );

      print('计划详情API响应: $response');

      if (response != null && response['data'] != null) {
        final data = response['data'];

        // 填充表单数据
        final planName = data['planName']?.toString() ?? '';
        planNameController.text = planName;
        planNameDisplay.value = planName;
        
        // stepCount 步数
        if (data['stepCount'] != null && data['stepCount'].toString().isNotEmpty) {
          final stepCountStr = data['stepCount'].toString();
          stepCountController.text = stepCountStr;
          stepCountDisplay.value = stepCountStr;
          // 只要有步数数据（即使是0），也标记为已输入
          hasStepCountInput.value = true;
          print('步数已加载: $stepCountStr, hasStepCountInput: ${hasStepCountInput.value}');
        }
        
        // exerciseDuration 对应时长
        if (data['exerciseDuration'] != null) {
          final duration = data['exerciseDuration'];
          final durationStr = duration is double 
              ? duration.toInt().toString() 
              : duration.toString();
          durationController.text = durationStr;
          durationDisplay.value = durationStr;
          print('时长已加载: $durationStr');
        }
        
        // exerciseCalorie 对应运动卡路里
        if (data['exerciseCalorie'] != null) {
          final calorie = data['exerciseCalorie'];
          final calorieStr = calorie is double 
              ? calorie.toInt().toString() 
              : calorie.toString();
          exerciseCalorieController.text = calorieStr;
          exerciseCalorieDisplay.value = calorieStr;
          print('运动卡路里已加载: $calorieStr');
        }
        
        // calorie 对应饮食卡路里
        if (data['calorie'] != null) {
          final calorie = data['calorie'];
          final calorieStr = calorie is double 
              ? calorie.toInt().toString() 
              : calorie.toString();
          dietCalorieController.text = calorieStr;
          dietCalorieDisplay.value = calorieStr;
          print('饮食卡路里已加载: $calorieStr');
        }
        
        // planCycle 计划周期（如果API返回的话）
        if (data['planCycle'] != null) {
          planCycle.value = int.tryParse(data['planCycle'].toString()) ?? 30;
        }
        
        // isDefault 是否默认计划
        if (data['isDefault'] != null) {
          isDefaultPlan.value = data['isDefault'] == 1;
        }

        // 填充事件打卡数据 - checkInEvent 是逗号分隔的字符串
        if (data['checkInEvent'] != null && data['checkInEvent'].toString().isNotEmpty) {
          final events = data['checkInEvent'].toString().split(',')
              .map((e) => e.trim())
              .where((e) => e.isNotEmpty)
              .toList();
          
          // 将API返回的事件添加到可用事件列表中（如果不存在）
          for (var event in events) {
            if (!availableEvents.contains(event)) {
              availableEvents.add(event);
            }
          }
          
          selectedEvents.value = events;
        }
        
        // 填充睡眠质量
        if (data['sleepQuality'] != null) {
          sleepQuality.value = data['sleepQuality'].toString();
        }
        
        // 填充情绪管理
        if (data['emotionManagement'] != null) {
          emotionManagement.value = data['emotionManagement'].toString();
        }
        
        // 保存计划状态
        if (data['planStatus'] != null) {
          currentPlanStatus = data['planStatus'].toString();
          print('计划状态: $currentPlanStatus');
        }

        print('计划详情加载成功: ${data['planName']}');
      }
    } catch (e) {
      print('加载计划详情失败: $e');
      Toast.show('加载计划详情失败');
    } finally {
      isLoading.value = false;
      isLoadingFromApi.value = false; // 加载完成
    }
  }

  void _setupListeners() {
    // 监听步数输入变化
    stepCountController.addListener(() {
      // 如果正在从API加载数据，不触发自动计算
      if (isLoadingFromApi.value) {
        return;
      }
      
      final stepCount = stepCountController.text;
      if (stepCount.isNotEmpty && int.tryParse(stepCount) != null) {
        hasStepCountInput.value = true;
        _calculateRecommendedValues(int.parse(stepCount));
      } else {
        hasStepCountInput.value = false;
        _clearRecommendedValues();
      }
    });
  }

  void _calculateRecommendedValues(int stepCount) {
    // 根据步数计算推荐值
    _getExerciseInfo(stepCount.toString());
  }

  void _clearRecommendedValues() {
    recommendedDuration.value = 0;
    recommendedExerciseCalorie.value = 0;
    recommendedDietCalorie.value = 0;
    durationController.clear();
    exerciseCalorieController.clear();
    dietCalorieController.clear();
  }

  Future<void> _getExerciseInfo(String stepCount) async {
    try {
      final result = await _api.queryExerciseInfoGet<Map<String, dynamic>>(
        stepCount: stepCount,
        isShowLoading: false,
      );
      print(result);
      if (result!['data'] != null) {
        durationController.text =
            result!['data']['exerciseDuration'].toString();
        exerciseCalorieController.text =
            result!['data']['exerciseCalorie'].toString();
        dietCalorieController.text = result!['data']['calorie'].toString();
      }
    } catch (e) {
      Toast.show('获取推荐值失败');
    }
  }

  void updatePlanCycle(int cycle) {
    planCycle.value = cycle;
  }

  Future<void> _loadHrvInfo() async {
    try {
      isLoadingHrv.value = true;
      final result = await _api.queryPlanHrvInfoGet<Map<String, dynamic>>(
        isShowLoading: false,
      );

      if (result?['msg'] != null) {
        hrvValue.value = '${result?['msg']}';
      } else if (result?['msg'] != null) {
        hrvValue.value = result!['msg'].toString();
      } else {
        hrvValue.value = '暂未形成基线';
      }
    } catch (e) {
      print('获取HRV信息失败: $e');
      hrvValue.value = '暂未形成基线';
    } finally {
      isLoadingHrv.value = false;
    }
  }

  void toggleDefaultPlan() {
    isDefaultPlan.value = !isDefaultPlan.value;
  }

  void toggleEvent(String event) {
    if (selectedEvents.contains(event)) {
      selectedEvents.remove(event);
    } else {
      selectedEvents.add(event);
    }
  }

  /// 添加自定义事件
  void addCustomEvent() {
    final eventName = customEventController.text.trim();
    if (eventName.isEmpty) {
      Toast.show('请输入事件名称');
      return;
    }

    // 检查是否已存在
    if (availableEvents.contains(eventName)) {
      Toast.show('该事件已存在');
      return;
    }

    // 添加到可用事件列表
    availableEvents.add(eventName);
    // 自动选中新添加的事件
    selectedEvents.add(eventName);
    // 清空输入框
    customEventController.clear();
  }

  /// 删除事件（长按删除）
  void deleteEvent(String event) {
    Get.dialog(
      AlertDialog(
        backgroundColor: const Color(0xFF282528),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: const Text('删除事件', style: TextStyle(color: Colors.white)),
        content: Text(
          '确定要删除"$event"吗？',
          style: const TextStyle(color: Colors.white70),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消', style: TextStyle(color: Colors.white70)),
          ),
          TextButton(
            onPressed: () {
              // 从可用事件列表中移除
              availableEvents.remove(event);
              // 如果已选中，也从选中列表中移除
              selectedEvents.remove(event);
              Get.back();
              Toast.show('已删除');
            },
            child: const Text('删除', style: TextStyle(color: Color(0xFFDB885F))),
          ),
        ],
      ),
    );
  }

  bool _validateForm() {
    if (planNameController.text.trim().isEmpty) {
      Toast.show('请输入计划名称');
      return false;
    }

    if (stepCountController.text.trim().isEmpty) {
      Toast.show('请输入步数目标');
      return false;
    }

    return true;
  }

  void _fillDefaultValues() {
    // 填充默认值
    if (durationController.text.trim().isEmpty) {
      durationController.text = '30';
    }
    if (exerciseCalorieController.text.trim().isEmpty) {
      exerciseCalorieController.text = '200';
    }
    if (dietCalorieController.text.trim().isEmpty) {
      dietCalorieController.text = '2000';
    }
  }

  Future<void> saveAndGeneratePlan() async {
    if (!_validateForm()) return;

    // 判断是否需要调用更新接口还是新增接口
    // 规则：编辑"已生成"（状态'2'）的计划 → 调用更新接口
    //      编辑"进行中"（状态'1'）或"已完成"（状态'3'）的计划 → 调用新增接口
    if (currentPlanId != null && currentPlanId!.isNotEmpty) {
      if (currentPlanStatus == '2') {
        // 已生成状态，调用更新接口
        await _updatePlanWithStatus('2');
        return;
      } else {
        // 进行中或已完成状态，调用新增接口生成新计划
        // 继续执行下面的新增逻辑
      }
    }

    // 检查是否有空值，如果有则填充默认值并提示
    bool hasEmptyValues = durationController.text.trim().isEmpty ||
        exerciseCalorieController.text.trim().isEmpty ||
        dietCalorieController.text.trim().isEmpty;

    if (hasEmptyValues) {
      final result = await Get.dialog<bool>(
        AlertDialog(
          backgroundColor: const Color(0xFF2D2D2D),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          title: const Text('提示', style: TextStyle(color: Colors.white)),
          content: const Text(
            '部分目标未填写，系统将使用基本值补充。事件打卡为可选项。\n\n是否继续保存？',
            style: TextStyle(color: Colors.white70),
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消', style: TextStyle(color: Colors.white70)),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              child:
                  const Text('继续', style: TextStyle(color: Color(0xFFDB885F))),
            ),
          ],
        ),
      );

      if (result != true) return;
      _fillDefaultValues();
    }

    await _savePlan(planStatus: '2'); // 已生成计划
  }

  Future<void> saveAndEnablePlan() async {
    if (!_validateForm()) return;

    // 判断是否需要调用启用接口还是新增接口
    // 规则：编辑"已生成"（状态'2'）的计划 → 调用启用接口
    //      编辑"进行中"（状态'1'）或"已完成"（状态'3'）的计划 → 调用新增接口
    if (currentPlanId != null && currentPlanId!.isNotEmpty) {
      if (currentPlanStatus == '2') {
        // 已生成状态，调用启用接口
        await _enablePlan();
        return;
      } else {
        // 进行中或已完成状态，调用新增接口生成新计划
        // 继续执行下面的新增逻辑
      }
    }

    // 检查是否有空值
    bool hasEmptyValues = durationController.text.trim().isEmpty ||
        exerciseCalorieController.text.trim().isEmpty ||
        dietCalorieController.text.trim().isEmpty;

    if (hasEmptyValues) {
      final result = await Get.dialog<bool>(
        AlertDialog(
          backgroundColor: const Color(0xFF2D2D2D),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          title: const Text('提示', style: TextStyle(color: Colors.white)),
          content: const Text(
            '部分目标未填写，系统将使用基本值补充。事件打卡为可选项。\n\n是否继续保存并启用？',
            style: TextStyle(color: Colors.white70),
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消', style: TextStyle(color: Colors.white70)),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              child: const Text('继续', style: TextStyle(color: Color(0xFFDB885F))),
            ),
          ],
        ),
      );

      if (result != true) return;
      _fillDefaultValues();
    }

    await _savePlan(planStatus: '1'); // 进行中计划
  }

  Future<void> _savePlan({required String planStatus}) async {
    try {
      isLoading.value = true;

      final result = await _api.addHealthPlanPost<Map<String, dynamic>>(
        planAssort: '1', // 1：自定义  2：AI报告 3：问卷生成
        planName: planNameController.text.trim(),
        planCycle: planCycle.value,
        planProgress: 0,
        planPoints: _calculatePlanPoints(),
        idDefault: isDefaultPlan.value ? '1' : '0',
        planStatus: planStatus,
        stepCount: int.tryParse(stepCountController.text) ?? 10000,
        sleepQuality: '良', // 固定优秀值
        restingHeartRate: '60-80', // 固定优秀值
        heartRateVariability: '30-50', // 固定优秀值
        bloodOxygenSaturation: '98', // 固定优秀值
        exerciseDuration: int.tryParse(durationController.text) ?? 30, // 运动时长
        exerciseCalorie: int.tryParse(exerciseCalorieController.text) ?? 200, // 运动卡路里
        calorie: int.tryParse(dietCalorieController.text) ?? 2000, // 饮食摄入卡路里
        checkInEvent: selectedEvents.join(','),
        emotionManagement: '20-30', // 固定优秀值
        isShowLoading: false,
      );
      print('API Response: $result');

      if (result != null && result['code'] == 200) {
        // 返回到主页面并切换到行动页tab
        final statusLogic = Get.find<StatusLogic>();
        statusLogic.changeTabIndex(3);
        Get.until((route) => route.isFirst);
        Toast.show(
          planStatus == '1' ? '计划已启用' : '计划已生成',
        );

        
      } else {
        if (result == null) {
          Toast.show(
            planStatus == '1' ? '计划已启用' : '计划已生成',
          );
          // 返回到主页面并切换到行动页tab
          final statusLogic = Get.find<StatusLogic>();
          statusLogic.changeTabIndex(3);
          Get.until((route) => route.isFirst);
        } else {
          Toast.show(result['message'] ?? '保存失败');
        }
      }
    } catch (e) {
      Toast.show('保存失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  int _calculatePlanPoints() {
    // 根据计划周期计算积分
    return planCycle.value * 1.5.round();
  }

  /// 启用计划
  Future<void> _enablePlan() async {
    if (!_validateForm()) return;
    
    if (currentPlanId == null) {
      Toast.show('计划ID不存在');
      return;
    }

    // 检查是否有空值
    bool hasEmptyValues = durationController.text.trim().isEmpty ||
        exerciseCalorieController.text.trim().isEmpty ||
        dietCalorieController.text.trim().isEmpty;

    if (hasEmptyValues) {
      final result = await Get.dialog<bool>(
        AlertDialog(
          backgroundColor: const Color(0xFF282528),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          title: const Text('提示', style: TextStyle(color: Colors.white)),
          content: const Text(
            '部分目标未填写，系统将使用基本值补充。事件打卡为可选项。\n\n是否继续启用？',
            style: TextStyle(color: Colors.white70),
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消', style: TextStyle(color: Colors.white70)),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              child: const Text('继续', style: TextStyle(color: Color(0xFFDB885F))),
            ),
          ],
        ),
      );

      if (result != true) return;
      _fillDefaultValues();
    }

    try {
      isLoading.value = true;

      // 判断计划类型：如果是从问卷生成的，使用 '3'，否则使用 '1'
      final planAssort = isViewMode.value ? '3' : '1';
      
      final result = await _api.enableHealthPlanPost<Map<String, dynamic>>(
        id: int.parse(currentPlanId!),
        planAssort: planAssort,
        planName: planNameController.text.trim(),
        planCycle: planCycle.value,
        planProgress: 0,
        planPoints: _calculatePlanPoints(),
        idDefault: isDefaultPlan.value ? '1' : '0',
        planStatus: '1', // 启用后状态为进行中
        stepCount: int.tryParse(stepCountController.text) ?? 10000,
        sleepQuality: sleepQuality.value,
        restingHeartRate: '60-80',
        heartRateVariability: '30-50',
        bloodOxygenSaturation: 98,
        calorie: int.tryParse(dietCalorieController.text) ?? 2000,
        checkInEvent: selectedEvents.join(','),
        emotionManagement: emotionManagement.value,
        deviceSn: '', // 根据实际情况填充
        isShowLoading: false,
      );

      if (result != null && result['code'] == 200) {
        Toast.show('计划已启用');
        // 退出编辑模式，回到查看模式
        isEditMode.value = false;
        // 重新加载计划详情以显示最新数据
        await _loadPlanDetail(currentPlanId!);
      } else {
        Toast.show(result?['message'] ?? '启用失败');
      }
    } catch (e) {
      Toast.show('启用失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 更新计划并设置状态
  Future<void> _updatePlanWithStatus(String planStatus) async {
    if (!_validateForm()) return;
    
    if (currentPlanId == null) {
      Toast.show('计划ID不存在');
      return;
    }

    // 检查是否有空值
    bool hasEmptyValues = durationController.text.trim().isEmpty ||
        exerciseCalorieController.text.trim().isEmpty ||
        dietCalorieController.text.trim().isEmpty;

    if (hasEmptyValues) {
      _fillDefaultValues();
    }

    try {
      isLoading.value = true;

      final result = await _api.updHealthPlanPost<Map<String, dynamic>>(
        id: int.parse(currentPlanId!),
        planAssort: '3', // 3：问卷生成
        planName: planNameController.text.trim(),
        planCycle: planCycle.value,
        planPoints: _calculatePlanPoints(),
        idDefault: isDefaultPlan.value ? '1' : '0',
        planStatus: planStatus, // 使用传入的状态
        stepCount: int.tryParse(stepCountController.text) ?? 10000,
        sleepQuality: sleepQuality.value,
        restingHeartRate: '60-80',
        heartRateVariability: '30-50',
        bloodOxygenSaturation: '98',
        exerciseDuration: int.tryParse(durationController.text) ?? 30,
        exerciseCalorie: int.tryParse(exerciseCalorieController.text) ?? 200,
        calorie: int.tryParse(dietCalorieController.text) ?? 2000,
        checkInEvent: selectedEvents.join(','),
        emotionManagement: emotionManagement.value,
        isShowLoading: false,
      );

      if (result != null && result['code'] == 200) {
        Toast.show(planStatus == '1' ? '计划已启用' : '计划已保存');
        // 退出编辑模式，回到查看模式
        isEditMode.value = false;
        // 重新加载计划详情以显示最新数据
        if (currentPlanId != null) {
          await _loadPlanDetail(currentPlanId!);
        }
      } else {
        Toast.show(result?['message'] ?? '保存失败');
      }
    } catch (e) {
      Toast.show('保存失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 更新计划
  Future<void> updatePlan() async {
    if (!_validateForm()) return;
    
    if (currentPlanId == null) {
      Toast.show('计划ID不存在');
      return;
    }

    // 检查是否有空值
    bool hasEmptyValues = durationController.text.trim().isEmpty ||
        exerciseCalorieController.text.trim().isEmpty ||
        dietCalorieController.text.trim().isEmpty;

    if (hasEmptyValues) {
      final result = await Get.dialog<bool>(
        AlertDialog(
          backgroundColor: const Color(0xFF282528),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          title: const Text('提示', style: TextStyle(color: Colors.white)),
          content: const Text(
            '部分目标未填写，系统将使用基本值补充。事件打卡为可选项。\n\n是否继续保存？',
            style: TextStyle(color: Colors.white70),
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消', style: TextStyle(color: Colors.white70)),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              child: const Text('继续', style: TextStyle(color: Color(0xFFDB885F))),
            ),
          ],
        ),
      );

      if (result != true) return;
      _fillDefaultValues();
    }

    try {
      isLoading.value = true;

      // 判断计划类型：如果是从问卷生成的，使用 '3'，否则使用 '1'
      final planAssort = isViewMode.value ? '3' : '1';
      
      final result = await _api.updHealthPlanPost<Map<String, dynamic>>(
        id: int.parse(currentPlanId!),
        planAssort: planAssort,
        planName: planNameController.text.trim(),
        planCycle: planCycle.value,
        planPoints: _calculatePlanPoints(),
        idDefault: isDefaultPlan.value ? '1' : '0',
        stepCount: int.tryParse(stepCountController.text) ?? 10000,
        sleepQuality: sleepQuality.value,
        restingHeartRate: '60-80',
        heartRateVariability: '30-50',
        bloodOxygenSaturation: '98',
        exerciseDuration: int.tryParse(durationController.text) ?? 30,
        exerciseCalorie: int.tryParse(exerciseCalorieController.text) ?? 200,
        calorie: int.tryParse(dietCalorieController.text) ?? 2000,
        checkInEvent: selectedEvents.join(','),
        emotionManagement: emotionManagement.value,
        isShowLoading: false,
      );

      if (result != null && result['code'] == 200) {
        Toast.show('计划已更新');
        // 退出编辑模式，回到查看模式
        isEditMode.value = false;
        // 重新加载计划详情以显示最新数据
        if (currentPlanId != null) {
          await _loadPlanDetail(currentPlanId!);
        }
      } else {
        Toast.show(result?['message'] ?? '更新失败');
      }
    } catch (e) {
      Toast.show('更新失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  @override
  void onClose() {
    planNameController.dispose();
    stepCountController.dispose();
    durationController.dispose();
    exerciseCalorieController.dispose();
    dietCalorieController.dispose();
    customEventController.dispose();
    super.onClose();
  }
}
